<template>
  <view class="min-h-screen bg-[#f6f8fb] p-4 flex flex-col items-center">
    <view class="w-[360px]">
      <button
        class="w-full h-[auto] rounded-xl border-2 border-dashed border-[#d7e6ff] flex items-center justify-center mb-6 bg-white"
        @click="handleAddClick"
      >
        <view
          class="h-[100rpx] flex items-center gap-2 text-[#3b82f6] font-medium"
        >
          <wd-icon name="user" color="#3b82f6" size="30rpx"></wd-icon>
          <text>新增联系人</text>
        </view>
      </button>
      <view class="flex flex-col gap-3">
        <view
          v-for="u in lists"
          :key="u.id"
          class="flex items-center justify-between bg-white rounded-2xl p-3 shadow-sm"
          @click="handleSelect(u)"
        >
          <view class="flex items-center justify-between text-f">
            <image
              :src="u.avatar"
              class="w-[80rpx] h-[80rpx] rounded-full mr-3"
              mode="aspectFill"
            />
            <view class="flex-1">
              <view class="text-base font-semibold text-[#111827]">{{
                u.name
              }}</view>
              <view class="text-sm text-[#6b7280] mt-0.5">{{ u.phone }}</view>
              <view class="text-[20rpx] text-[#999] mt-1">{{
                u.relation
              }}</view>
            </view>
          </view>
          <view>
            <wd-icon
              name="check-circle-filled"
              size="40rpx"
              color="#3b82f6"
              v-if="u.is_default"
            ></wd-icon>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { jumpTo } from '@/utils/unifunc'
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getContacts, updateContact } from '@/api/contact'
import useStore from '@/store'

const { useUser } = useStore()

const lists = ref<IContact[]>([])

const handleSelect = async (u: IContact) => {
  if (u.is_default === 1) {
    uni.showToast({
      title: '默认联系人不能取消',
      icon: 'none'
    })
    return
  }
  const res = await updateContact<
    {
      id: number
      is_default: number
    },
    IContact
  >({
    id: u.id,
    is_default: 1
  })
  if (res.code === 200) {
    uni.showToast({
      title: '操作成功',
      icon: 'success'
    })
  } else {
    uni.showToast({
      title: res.msg || '操作失败',
      icon: 'none'
    })
  }
  for (const item of lists.value) {
    item.is_default = 0
  }
  u.is_default = 1
}

const handleAddClick = () => {
  jumpTo('/pages/my/linkAdd')
}

onShow(async () => {
  const res = await getContacts<IPaginationParams, IContact>({
    page: 1,
    pageSize: 100,
    user_id: useUser.getUser.id
  })
  if (res.code === 200) {
    lists.value = res.data.items
  }
})
</script>
